import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Random;

@WebServlet("/guess")
public class GuessServlet extends HttpServlet {
    // 这里的 ToGuess 表示要猜的数字
    private int ToGuess = 0;
    // 这里的 count 表示本次猜了的次数
    private int count = 0;
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=utf-8");
        Random random = new Random();
        ToGuess = random.nextInt(100)+1;
        count = 0;
        StringBuilder html = new StringBuilder();
        html.append("<form action=\"guess\" method=\"POST\">");
        html.append("<input type=\"text\" name=\"num\">");
        html.append("<input type=\"submit\" value=\"提交\">");
        html.append("</form>");
        resp.getWriter().write(html.toString());
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=utf-8");
        String str = req.getParameter("num");
        int num = Integer.parseInt(str);
        String res = "";
        count++;
        if(num > ToGuess){
            res = "猜大了";
        }else if (num < ToGuess){
            res = "猜小了";
        }else {
            res = "猜对了";
        }
        StringBuilder html = new StringBuilder();
        html.append("<form action=\"guess\" method=\"POST\">");
        html.append("<input type=\"text\" name=\"num\">");
        html.append("<input type=\"submit\" value=\"提交\">");
        html.append("</form>");
        html.append("<div>"+res+"</div>");
        html.append("<div>当前猜了: "+count+"次</div>");
        resp.getWriter().write(html.toString());
    }
}
